<?php
namespace App\Http\Controllers\Wx;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\AliSms;
use App\Services\RedisService;
use App\Services\TencentMap;
use App\Repos\UserRepo;
use App\Models\Product;
use App\Models\Cate;
use App\Models\Notice;
use App\Models\Shop;
use App\Models\System;
use App\Models\ProductCity;
use App\Models\Faq;
use App\Models\City;
use App\Models\Wxuser;
use DB;
use EasyWeChat;
use Log;

class IndexController extends Controller
{
    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public function serve()
    {
        Log::info('request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志

        $app = app('wechat.official_account');
        //dd($app);
        $app->server->push(function($message){
         
            //return "欢迎关注!业务问题请加微信 bzs1984 咨询，谢谢。";        
           return env('WELCOME_MSG', '欢迎关注!');
            
        });

        return $app->server->serve();
    }

    // 返回openid    
    public function getOpenid(Request $request)
    {
        $rs['status'] = false;
        $code = trim($request->code);
        $mini = EasyWeChat::miniProgram(); // 小程序
        $result = $mini->auth->session($code); // $code 为wx.login里的code
        if(!array_key_exists('openid', $result)) {
            $rs['msg'] = $result['errmsg'];
            return response()->json($rs);
        }
        $rs['status'] = true;
        $rs['openid']      = $result['openid'];
        $rs['session_key'] = $result['session_key'];
        return response()->json($rs);
    }

    /**
     * 获取微信用户信息
     */
    public function getWxUser(Request $request)
    {
        $rs['status'] = false;      
        $session     = $request->session_key;
        $iv          = $request->iv;
        $encryptData = $request->encryptData;
        $app         = EasyWeChat::miniProgram(); // 小程序
        $decryptedData = $app->encryptor->decryptData($session, $iv, $encryptData);
        if($decryptedData) {
            $rs['status'] = true;
            $rs['data'] = $decryptedData;            
            return response()->json($rs);
        }
        return response()->json($rs);
    }
   
    // 小程序验证身份获取token
    public function getToken(Request $request)
    {
        $rs['status'] = true;
        $data = array_only($request->all(),['longitude','latitude','avatar','nickname','name','mobile','unionid','small_openid']);

        $where['mobile'] = $data['mobile'];
        $has = UserRepo::find($where);
        // 还没确实是否要验证手机 所有先保留
        if($has && $has->status!=1) {
            $rs['status'] = false;
            $rs['msg']    = '账号被冻结，请通过商品详情中的快捷导航联系客服';
            return response()->json($rs); 
        }
        $user = UserRepo::create($data);
        $rs['data']['token']   = $user->token;
        $rs['data']['user_id'] = $user->id;
        return response()->json($rs);   
    }

    
   

   

    public function upload(Request $request)
    {
        $rs['status'] = true;
        $folder       = 'uploads/'.date('Ymd');
        
        if ($request->isMethod('post')) {
            $file = $request->file('file');

            // 文件是否上传成功
            if ($file->isValid()) {                
                $path = '/'.$file->store($folder);                    
                
                $rs['data'] = $path;
                return response()->json($rs);
            }

        }
        return response()->json(['rs' => false, 'msg' => '不是正确请求方式']);
    }


    public function notice(Request $request)
    {
        $rs['status'] = true;       
        $data         = Notice::take(5)
                        ->orderBy('created_at','desc')
                        ->get();
        $rs['data'] = $data;
        return response()->json($rs);
    }

    public function noticeInfo(Request $request)
    {
        $rs['status'] = true; 
        $id           = (int)$request->id;      
        $data         = Notice::find($id);
        $rs['data'] = $data;
        return response()->json($rs);
    }

    public function faq(Request $request)
    {
        $rs['status'] = true;       
        $data         = Faq::take(10)
                        ->orderBy('created_at','desc')
                        ->get();
        $rs['data'] = $data;
        return response()->json($rs);
    }

    public function faqInfo(Request $request)
    {
        $rs['status'] = true; 
        $id           = (int)$request->id;      
        $data         = Faq::find($id);
        $rs['data'] = $data;
        return response()->json($rs);
    }

    public function cate(Request $request)
    {
        $rs['status']     = true;
       
        $list = Cate::select(['id','name','weight'])
                        ->orderBy('weight','asc')
                        ->get();
        $rs['data'] = $list;
        return response()->json($rs);
    }

    /**
     * 首页推荐的商品
     */
    public function recProduct(Request $request)
    {
        $rs['status']     = true;
        $where['status'] = 1;
        $where['is_rec'] = 1;
       
        $query = Product::query()->where($where);
        if($request->city) {
            $cityname = trim($request->city);
            $product_ids = DB::table('cities as a')
            ->join('product_cities as b','a.id','=','b.city_id')            
            ->where('a.name',$cityname)
            ->pluck('b.product_id')  ;
            if($product_ids) {
                $query->where(function($query) use($product_ids){
                    $query->where('all_country',1);
                    $query->orWhereIn('id',$product_ids);
                });
                
            } 

        } else {
            $query->where('all_country',1);
        }
       
        $list  = $query->orderBy('created_at','desc')
                        ->paginate(100);
        $rs['data'] = $list;
        return response()->json($rs);
    }

     /**
     * 首页热销的商品
     */
    public function hotProduct(Request $request)
    {
        $rs['status']     = true;
        $where['status'] = 1;
        $where['is_hot'] = 1;
       
        
        $query = Product::query()->where($where);
        if($request->city) {
            $cityname = trim($request->city);
            $product_ids = DB::table('cities as a')
            ->join('product_cities as b','a.id','=','b.city_id')            
            ->where('a.name',$cityname)
            ->pluck('b.product_id')  ;
            if($product_ids) {
                $query->where(function($query) use($product_ids){
                    $query->where('all_country',1);
                    $query->orWhereIn('id',$product_ids);
                });
                
            } 

        } else  {
            $query->where('all_country',1);
        }

        $list = $query->orderBy('created_at','desc')
                        ->take(3)->get();
        $rs['data'] = $list;
        return response()->json($rs);
    }

    public function shopInfo(Request $request)
    {
        $rs['status']     = true;
        $where['status'] = 1;
        $where['id'] = $request->shop_id;
        $data = Shop::where($where)->first();
        $rs['data'] = $data;
        return response()->json($rs);
    }

    // 发送短信接口
    public function sendSms(Request $request)
    {
        $mobile = $request->mobile;
        $code = mt_rand(1000,9999);

        $flag = AliSms::sendMsg($mobile,$code);
        //dd($flag);
        $rs['status'] = true;
        $rs['data']['code'] = $code;
        RedisService::set('pintuan:sms:'.$mobile,$code);
        return response()->json($rs);
    }

    // 验证短信验证码
    public function checkSms(Request $request)
    {
        $rs['status'] = false;
        $rs['msg']    = '验证码错误';
        $mobile = trim($request->mobile);
        $code   = trim($request->code);
        $smsCode = RedisService::get('pintuan:sms:'.$mobile);
        if($code == $smsCode) {

            $rs['status'] = true;
            $rs['msg']    = '验证码正确';
            RedisService::del('pintuan:sms:'.$mobile);
        }
        return response()->json($rs);
    }

    // 拼团规则说明
    public function groupRule(Request $request)
    {
        $rs['status'] = true;
        $rs['data'] = System::value('group_rule');
        return response()->json($rs);
    }


    public function getSmallcode(Request $request)
    {
        $value = $request->scene_value;
        $app = EasyWeChat::miniProgram(); // 小程序
        $page = 'pages/paySuccess/paySuccess';
        if($request->type == 'product-info') {
            $page = 'pages/goodsDetails/goodsDetails';
        }  
        $response = $app->app_code->getUnlimit($value, [
            'page'  => $page,
            'width' => 300,
        ]);
        
        $name = md5($value);
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save('uploads/smallcode', $name.'.png');
            $rs['status'] = true;
            $rs['data'] = 'uploads/smallcode/'.$filename;
            return response()->json($rs);
        }
    }

    public function getCity(Request $request)
    {
        $rs['status'] = true;
        $latlng = $request->latlng;
        $data = TencentMap::coordiateToAddress($latlng);
        $rs['data'] = $data;
        return response()->json($rs);
    }

   

    
   


    
}
